package cn.simon.service.Impl;

import cn.simon.mapper.OrderMapper;
import cn.simon.mapper.SeckillGoodsMapper;
import cn.simon.mapper.SeckillOrderMapper;
import cn.simon.pojo.Order;
import cn.simon.pojo.SeckillGoods;
import cn.simon.pojo.SeckillOrder;
import cn.simon.pojo.User;
import cn.simon.service.IGoodsService;
import cn.simon.service.IOrderService;
import cn.simon.service.ISeckillGoodsService;
import cn.simon.service.ISeckillOrderService;
import cn.simon.util.MD5Util;
import cn.simon.util.UUIDUtil;
import cn.simon.vo.GoodsVo;
import cn.simon.vo.OrderVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 * simon-yian 开心
 * @author simon-yian

 */
@Log
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Autowired
    private SeckillGoodsMapper seckillGoodsMapper;

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private SeckillOrderMapper seckillOrderMapper;
    @Autowired
    private IGoodsService iGoodsService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ISeckillGoodsService seckillGoodsService;


    public Order seckill(User user, GoodsVo goods) {
        ValueOperations valueOperations = redisTemplate.opsForValue();

        SeckillGoods seckillGoods = seckillGoodsMapper.selectOne(new QueryWrapper<SeckillGoods>()
                .eq("goods_id",goods.getId()));
        log.info("秒杀商品："+seckillGoods);

        seckillGoods.setStockCount(seckillGoods.getStockCount()-1);
//        seckillGoodsMapper.updateById(seckillGoods);

        boolean update = seckillGoodsService.update(new UpdateWrapper<SeckillGoods>()
                .setSql("stock_count = " + "stock_count-1")
                .eq("goods_id", goods.getId())
                .gt("stock_count", 0));
        if (seckillGoods.getStockCount() < 0){
            //判断是否还有库存
            valueOperations.set("isStockEmpty:" + goods.getId(),0);
            return null;
        }


        Order order = new Order();
        order.setUserId(user.getId());
        order.setGoodsId(goods.getId());
        order.setDeliveryAddrId(0l);
        order.setGoodsName(goods.getGoodsName());
        order.setGoodsCount(1);
        order.setGoodsPrice(goods.getSeckillPrice());
        order.setOrderChannel(1);
        order.setStatus(0);
        order.setCreateDate(new Date());



        log.info("订单插入之前——："+order);
        orderMapper.insert(order);
        log.info("订单插入之后+++++++++："+order);
        //插入秒杀订单
        SeckillOrder seckillOrder =new  SeckillOrder();
                seckillOrder.setOrderId(order.getId());
        seckillOrder.setGoodsId(goods.getId());
        seckillOrder.setUserId(user.getId());

        seckillOrderMapper.insert(seckillOrder);

        redisTemplate.opsForValue().set("userId:"+user.getId()+":"+goods.getId(),seckillOrder);

        return order;
    }

    @Override
    public Order findOrderByorderId(Long orderId) {
        return orderMapper.selectById(orderId);
    }

    /**
     * @功能描述: 创建随机秒杀访问地址path
     * @Param:
     * @Return:
     * @Author simon-yi'an
     * @Date 2022/11/9 22:36
     */
    @Override
    public String createPath(User user, Long goodsId) {
        String path = MD5Util.md5(UUIDUtil.uuid()+"123456") ;
        redisTemplate.opsForValue().set("seckillPath:"+user.getId()+":"+goodsId,path,60, TimeUnit.SECONDS);
        return path;
    }
    /**
     * @功能描述: 秒杀地址校验
     * @Param:
     * @Return:
     * @Author simon-yi'an
     * @Date 2022/11/9 23:20
     */
    @Override
    public boolean checkPath(User user, Long goodsId, String path) {
        if (user == null || goodsId < 0 || StringUtils.isEmpty(path)){
            return false;
        }
        String checkPath = (String) redisTemplate.opsForValue().get("seckillPath:"+user.getId()+":"+goodsId);
        log.info("checkPath+++++++++++"+checkPath);
        log.info("Path+++++++++++"+path);
        if(path.equals(checkPath)){
            return true;
        }
        return false;
    }

    /**
     * @功能描述: 校验秒杀验证码
     * @Param:
     * @Return:
     * @Author simon-yi'an
     * @Date 2022/11/10 11:28
     */
    @Override
    public boolean checkCaptcha(User user, Long goodsId, String captcha) {
        if (user == null || goodsId < 0 || StringUtils.isEmpty(captcha)){
            return false;
        }
        String str = (String)redisTemplate.opsForValue().get("captcha:"+user.getId()+":"+goodsId);
        return captcha.equals(str);
    }
}
